const express = require('express')

const app = express()
// 导入并配置cors中间件
const cors = require('cors')
app.use(cors())

// 配置解析表单数据中间件
app.use(express.urlencoded({extended:false}))
// 解析json数据
app.use(express.json())

// 定义失败返回结果中间件
app.use((req,res,next) => {
  res.cc = function(err,status=1) {
    res.send({
      status,
      message:err instanceof Error?err.message:err
    })
  }
  next()
})

// 一定要在路由之前导入解析token中间件
const expressJwt = require('express-jwt')
const config = require('./config')

app.use(expressJwt({secret:config.jtwSecreKey}).unless({path:[/^\/api/]}))

// 导入路由
const router = require('./router/user')
const userInfoRouter = require('./router/userInfo')
const articleRouter = require('./router/article')
const { log } = require('async')
app.use('/api',router)
app.use('/my',userInfoRouter)
app.use('/my/article',articleRouter)
// 定义错误级别中间件
app.use((err,req,res,next) => {
  console.log('请求路径:', req.path) // 添加这行
  // console.log(err,"err")
  if(err.name === 'UnauthorizedError') return res.cc('身份认证失败')
  // 位未知错误
res.cc(err)
})

// 修改监听部分
const port = process.env.PORT || 3007
app.listen(port, () => {
  console.log(`api server running at port ${port}`);
})